package com.wash.car.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pmo.boot.common.BizException;
import com.wash.car.biz.OrderServer;
import com.wash.car.dao.domain.AbBaseDomain;
import com.wash.car.dao.domain.CarOrderDomain;
import com.wash.car.dao.domain.CarVipDomain;
import com.wash.car.dao.mapper.CarOrderMapper;
import com.wash.car.dao.mapper.CarVipMapper;
import com.wash.car.dao.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class OrderServerImpl implements OrderServer {

    @Resource
    private CarOrderMapper orderMapper;
    @Resource
    private CarVipMapper carVipMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void add(OrderAddModel model) {
        CarVipDomain dbVipDomain = carVipMapper.selectOne(new CarVipDomain().setPlate(model.getPlate()));
        if (ObjectUtil.isEmpty(dbVipDomain)) {
            throw BizException.error("9995", "您不是会员,请联系老板充值！");
        }
        if (DateUtil.compare(dbVipDomain.getEndTime(), DateUtil.endOfDay(new Date())) < 0) {
            throw BizException.error("9995", "您的会员已过期,请联系老板充值！");
        }
        if (orderMapper.inTheQueue(model.getPlate()) > 0) {
            throw BizException.error("9995", "该车辆已经在排队中！");
        }
        Integer queueNumber = stringRedisTemplate.opsForValue().increment("queue:" + model.getStoreId(), 1L).intValue();
        CarOrderDomain addOrderDomain = AbBaseDomain.setDefaultValue(CarOrderDomain.class)
                .setCode(String.format("%04d", queueNumber)).setPlate(model.getPlate())
                .setUserId(model.getUserId()).setStoreId(model.getStoreId());
        orderMapper.insertSelective(addOrderDomain);
    }


    @Override
    public void del(OrderDeleteModel model) {
        CarOrderDomain dbCarOrderDomain = orderMapper.selectByPrimaryKey(model.getId());
        if (ObjectUtil.isNotEmpty(dbCarOrderDomain)) {
            if (dbCarOrderDomain.getState() != 0) {
                throw BizException.error("9995", "只有在排队中的订单才能取消！");
            }
            int i = orderMapper.delete((CarOrderDomain) new CarOrderDomain().setId(model.getId()));
            log.info("取消排队结果：{}", i);
        }
    }

    @Override
    public void updateState(OrderUpdateModel model) {
        CarOrderDomain domain = BeanUtil.copyProperties(model, CarOrderDomain.class);
        orderMapper.updateByPrimaryKeySelective(domain);
    }


    @Override
    public List<String> findVehicles(Long userId) {
        return orderMapper.selectVehicles(userId);
    }

    @Override
    public StoreQueueModel findStoreQueueCount(Long storeId) {
        Integer count = orderMapper.selectStoreQueueCount(storeId);
        return new StoreQueueModel().setCount(count);
    }


    @Override
    public List<OrderDetailsModel> findOrderDetails(OrderWhereModel model) {
        return orderMapper.selectOrderDetails(BeanUtil.beanToMap(model));
    }


    @Override
    public List<OrderDetailsModel> findOrderQueueDetails(OrderWhereModel model) {
        Date date = new Date();
        model.setStartDate(DateUtil.beginOfDay(date));
        model.setEndDate(DateUtil.endOfDay(date));
        List<OrderDetailsModel> userQueueOrderList = findOrderDetails(model);
        userQueueOrderList.forEach(s1 -> {
            OrderWhereModel model1 = new OrderWhereModel().setStoreId(s1.getStoreId())
                    .setStartDate(DateUtil.beginOfDay(date))
                    .setEndDate(DateUtil.endOfDay(date))
                    .setStates(ListUtil.toList(new Integer[]{0}));
            List<OrderDetailsModel> storeOrderList = findOrderDetails(model1);
            Long waitNumber = 0L;
            if (CollectionUtil.isNotEmpty(storeOrderList)) {
                waitNumber = storeOrderList.stream().filter(s2 ->
                        s1.getState() == 0 && DateUtil.compare(s2.getTime(), s1.getTime()) < 0).count();
            }
            s1.setWaitNumber(waitNumber.intValue());
        });
        return userQueueOrderList;
    }


    @Override
    public PageInfo<OrderDetailsModel> page(OrderPageWhereModel model) {
        PageHelper.startPage(model.getPageNum(), model.getPageSize(), model.getOrderBySql());
        List<OrderDetailsModel> list = orderMapper.selectOrderDetails(BeanUtil.beanToMap(model));
        PageInfo<OrderDetailsModel> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


}
